package com.hsd.znsh.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/*
 * @auther: wangjiacai
 *
 * @create: 2018-05-17 21:01:00
 */
public class PortUtil {

    public static boolean findPortInUsing(Integer port){
        String[] command="netstat -ano".split(" ");
        boolean portFlag=false;
        try {
            Process process = Runtime.getRuntime().exec(command);
            BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(process.getInputStream(),"gbk"));
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                String[] lines=line.split("\\s+");
                String os=System.getProperty("os.name").toLowerCase();
                if(os.startsWith("win")){
                    if(lines.length>5&&lines[2].indexOf(""+port)!=-1&&lines[4].equals("ESTABLISHED")){
                        System.out.println(line);
                        portFlag=true;
                        break;
                    }
                }else{
                    if(lines.length>7&&lines[3].indexOf(""+port)!=-1&&lines[5].equals("ESTABLISHED")){
                        System.out.println(line);
                        portFlag=true;
                        break;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            portFlag=true;
        }
        return portFlag;
    }

    public static boolean findPortInLisnter(Integer port){
        String[] command="netstat -ano".split(" ");
        try {
            Process process = Runtime.getRuntime().exec(command);
            BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(process.getInputStream(),"gbk"));
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                String[] lines=line.split("\\s+");
                String os=System.getProperty("os.name").toLowerCase();
                if(os.startsWith("win")){
                    if(lines.length>5&&lines[2].indexOf(""+port)!=-1&&lines[4].equals("LISTENING")){
                        System.out.println(line);
                        bufferedReader.close();
                        return true;
                    }
                }else{
                    if(lines.length>7&&lines[3].indexOf(""+port)!=-1&&lines[5].equals("LISTEN")){
                        System.out.println(line);
                        bufferedReader.close();
                        return true;
                    }
                }
            }
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
}
